<template>
  <div class="rich-text-editor">
    <Toolbar
      v-if="!inputDisabled"
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :default-config="toolbarConfig"
      :mode="mode" />
    <Editor
      :value="value || ''"
      style="height: 500px; overflow-y: hidden"
      :default-config="editorConfig"
      :mode="mode"
      @input="emitInput"
      @onCreated="onCreated" />
  </div>
</template>

<script>
  import '@wangeditor/editor/dist/css/style.css'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import formInput from '@/components/form/form-input'

  export default {
    name: 'RichTextEditor',
    components: {
      Editor,
      Toolbar
    },
    mixins: [formInput],
    props: {
      value: {
        type: String
      }
    },
    data() {
      return {
        editor: null,
        toolbarConfig: {},
        editorConfig: {
          readOnly: this.inputDisabled,
          placeholder: '请输入内容...',
          maxLength: 2000
        },
        mode: 'simple' // or 'simple'
      }
    },
    watch: {
      inputDisabled: {
        immediate: true,
        handler: 'handleDisabled'
      }
    },
    beforeDestroy() {
      this.editor?.destroy()
    },
    methods: {
      handleDisabled() {
        if (this.inputDisabled) {
          this.editor?.disable()
        } else {
          this.editor?.enable()
        }
      },
      onCreated(editor) {
        this.editor = Object.seal(editor)
        this.handleDisabled()
      },
      emitInput(val) {
        if (this.editor.isEmpty()) {
          this.$emit('input', '')
          return
        }
        this.$emit('input', val)
      }
    }
  }
</script>

<style lang="scss">
  .rich-text-editor {
    z-index: 4;
    overflow: hidden;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  .el-form-item.is-error {
    .rich-text-editor {
      border-color: #f56c6c;
    }
  }
</style>
